package com.xiaoyu.lanling.feature.fate.controller

import `in`.srain.cube.views.list.CubeRecyclerViewAdapter
import `in`.srain.cube.views.list.CubeRecyclerViewSimpleAdapter
import `in`.srain.cube.views.list.PagedListDataModelWithRequestTag
import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.base.view.list.BaseListViewController
import com.xiaoyu.lanling.event.fate.MainFateUserListEvent
import com.xiaoyu.lanling.event.coin.CoinAccostEvent
import com.xiaoyu.lanling.feature.fate.model.MainFateUserItem
import com.xiaoyu.lanling.feature.fate.viewholder.MainFateUserViewHolder
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MainFateUserListViewController(context: Context, listData: PagedListDataModelWithRequestTag<MainFateUserItem, Any>?, adapter: CubeRecyclerViewAdapter<MainFateUserItem>, swipeRefreshLayout: SwipeRefreshLayout?, recyclerView: RecyclerView?) : BaseListViewController<MainFateUserItem, Any>(context, listData, adapter, swipeRefreshLayout, recyclerView) {

    companion object {
        fun create(context: Context, listData: PagedListDataModelWithRequestTag<MainFateUserItem, Any>?, swipeRefreshLayout: SwipeRefreshLayout?, recyclerView: RecyclerView?): MainFateUserListViewController {

            val adapter = CubeRecyclerViewSimpleAdapter<MainFateUserItem>()
            adapter.setViewHolderClass(0, null, MainFateUserViewHolder::class.java, 20)

            val controller = MainFateUserListViewController(context, listData, adapter, swipeRefreshLayout, recyclerView)
            AppEventBus.bindContainerAndHandler(context, object : SimpleEventHandler() {

                @Subscribe(threadMode = ThreadMode.MAIN)
                fun onEvent(event: MainFateUserListEvent) {
                    controller.onListEvent(event)
                }

                @Subscribe(threadMode = ThreadMode.MAIN)
                fun onEvent(event: CoinAccostEvent) {
                    listData?.listPageInfo?.dataList?.forEachIndexed { index, item ->
                        if (item.user.uid == event.uid) {
                            item.selected = true
                            adapter.notifyItemChanged(index, item)
                            return@forEachIndexed
                        }
                    }
                }
            })
            return controller
        }
    }
}
